package com.md.youyouhui.net;

import android.content.Context;
import android.util.Log;

import com.md.youyouhui.utils.SharedPreferencesUtils;

import java.io.File;
import java.net.CookieHandler;
import java.net.CookieManager;
import java.net.CookiePolicy;
import java.util.concurrent.TimeUnit;

import okhttp3.Cache;
import okhttp3.OkHttpClient;
import okhttp3.Request;


/**
 * Created by YaWei on 2016/8/3.
 * contact zyawei@live.com.
 */
public class OkHttpUtils {
    private static OkHttpClient httpClient;
    private static OkHttpClient.Builder mOkHttpClient;

    public static OkHttpClient.Builder newInstance(Context context) {
        if (null == mOkHttpClient) {
            synchronized (OkHttpUtils.class) {
                if (null == mOkHttpClient) {
                    httpClient = new OkHttpClient();
                    mOkHttpClient = httpClient.newBuilder();
                    File cache = context.getCacheDir();
                    //设置超时和重连  
                    mOkHttpClient.cache(new Cache(cache, Constants.RESPONSE_CACHE_SIZE));
                    mOkHttpClient.readTimeout(Constants.HTTP_READ_TIMEOUT, TimeUnit.SECONDS);
                    mOkHttpClient.writeTimeout(Constants.HTTP_WRITE_TIMEOUT, TimeUnit.SECONDS);
                    mOkHttpClient.connectTimeout(Constants.HTTP_CONNECT_TIMEOUT, TimeUnit.SECONDS);
                    //错误重连  
                    mOkHttpClient.retryOnConnectionFailure(true);
                    mOkHttpClient.addInterceptor(chain -> {
                        String packageName = context.getPackageName();
                        String token = SharedPreferencesUtils.getString(context, Constants.USER_TOKEN, "");
                        Request.Builder builder = chain.request().newBuilder();
                        Request request = builder.addHeader("Token", token).addHeader("package","com.md.youyouhui").build();
                        Log.e("OkHttpUtils", "newInstance: " + token);
                        return chain.proceed(request);
                    });
                    CookieHandler.setDefault(getCookieManager());

                }
            }
        }
        return mOkHttpClient;
    }

    private static CookieManager getCookieManager() {
        CookieManager cookieManager = new CookieManager();
        cookieManager.setCookiePolicy(CookiePolicy.ACCEPT_ALL);
        return cookieManager;
    }


}
